<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>多AI对话比较-单轮（流式）</title>
    <!-- 引入 highlight.js 样式和核心库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
    <!-- 引入 marked.js 用于Markdown解析 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.2.12/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <!-- 引入语法高亮支持 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/json.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/bash.min.js"></script>
    <style>
        /* 保持之前的样式不变 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        /* 其他样式保持不变... */
    </style>
</head>
<body>
    <h1>多AI对话比较-单轮（流式响应）</h1>
    <div class="chat-container">
        <div class="input-area">
            <textarea id="prompt" placeholder="输入您的问题..." rows="3" autocomplete="off"></textarea>
            <button id="ask-button">提问</button>
        </div>

        <div class="responses-container">
            <div class="ai-response-container">
                <div class="ai-title">AI服务1</div>
                <div class="ai-content" id="ai1-response">等待问题...</div>
            </div>
            <div class="ai-response-container">
                <div class="ai-title">AI服务2</div>
                <div class="ai-content" id="ai2-response">等待问题...</div>
            </div>
            <div class="ai-response-container">
                <div class="ai-title">AI服务3</div>
                <div class="ai-content" id="ai3-response">等待问题...</div>
            </div>
        </div>
    </div>

    <script>
        // 配置 marked.js
        marked.setOptions({
            breaks: true,
            highlight: function(code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                }
                return hljs.highlightAuto(code).value;
            }
        });

        document.getElementById('ask-button').addEventListener('click', askAI);
        document.getElementById('prompt').addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                askAI();
            }
        });

        // 存储每个AI的流式数据
        const streamData = {
            ai1: '',
            ai2: '',
            ai3: ''
        };

        function askAI() {
            const prompt = document.getElementById('prompt').value.trim();
            if (!prompt) return;

            // 重置流式数据
            streamData.ai1 = '';
            streamData.ai2 = '';
            streamData.ai3 = '';

            // 显示加载状态
            document.getElementById('ai1-response').textContent = "思考中...";
            document.getElementById('ai2-response').textContent = "思考中...";
            document.getElementById('ai3-response').textContent = "思考中...";

            // 禁用按钮防止重复提交
            const button = document.getElementById('ask-button');
            button.disabled = true;
            button.textContent = "查询中...";

            // 使用EventSource或Fetch API的流式处理
            // 这里使用Fetch API的流式处理方式
            fetch('/chat/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: JSON.stringify({prompt: prompt})
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }

                // 检查是否支持流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let partialData = '';

                function readStream() {
                    return reader.read().then(({done, value}) => {
                        if (done) {
                            // 流结束
                            button.disabled = false;
                            button.textContent = "提问";
                            return;
                        }

                        // 处理流数据
                        const chunk = decoder.decode(value, {stream: true});
                        partialData += chunk;

                        // 尝试按行分割处理（假设后端以\n分割JSON）
                        const lines = partialData.split('\n');
                        partialData = lines.pop(); // 最后一行可能不完整

                        for (const line of lines) {
                            if (line.trim() === '') continue;
                            try {
                                const data = JSON.parse(line);
                                updateAIResponse(data);
                            } catch (e) {
                                console.error('解析JSON失败:', e, '原始数据:', line);
                            }
                        }

                        // 继续读取
                        return readStream();
                    });
                }

                return readStream();
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('ai1-response').innerHTML = `<p style="color: red;">出错: ${escapeHtml(error.message)}</p>`;
                button.disabled = false;
                button.textContent = "提问";
            });
        }

        // 更新AI响应（流式）
        function updateAIResponse(data) {
            if (data.ai1) {
                streamData.ai1 += data.ai1;
                processAndDisplayResponse('ai1-response', streamData.ai1);
            }
            if (data.ai2) {
                streamData.ai2 += data.ai2;
                processAndDisplayResponse('ai2-response', streamData.ai2);
            }
            if (data.ai3) {
                streamData.ai3 += data.ai3;
                processAndDisplayResponse('ai3-response', streamData.ai3);
            }
        }

        // 处理响应内容并解析Markdown
        function processAndDisplayResponse(elementId, content) {
            if (!content) {
                document.getElementById(elementId).innerHTML = "<p>无响应</p>";
                return;
            }

            // 使用marked.js解析Markdown
            const htmlContent = marked.parse(content);

            // 设置HTML内容
            document.getElementById(elementId).innerHTML = htmlContent;

            // 自动滚动到底部
            const element = document.getElementById(elementId);
            element.scrollTop = element.scrollHeight;
        }

        // HTML转义函数，用于安全显示错误消息
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 辅助函数获取CSRF token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    </script>
</body>
</html>